package com.lzx.adx.report.controller.v1.toutiao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.toutiao.request.TouTiaoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.DynamicRequestLimiter;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 产品：闲鱼
 * 媒体：今日头条
 */
@RequestMapping("/tt/kk")
@RestController
@Slf4j
public class TouTiaoKKController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private DynamicRequestLimiter dynamicRequestLimiter;

    @GetMapping("/report")
    public ResponseEntity report(TouTiaoRequest touTiaoRequest, HttpServletRequest request) {
        log.info("接收到今日头条到夸克的请求参数为{}",JsonUtils.toJsonString(touTiaoRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(touTiaoRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(touTiaoRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        reportDTO.setOaidSum(touTiaoRequest.getOaidMd5());
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(touTiaoRequest.getDspId());
        String resultUrl = KkHeper.covertHwKk(accountDTO, reportDTO);
        log.info("账号{}头条到夸克完整的url为{}", reportDTO.getDspId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号{}头条到夸克请求响应结果为{}", reportDTO.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId) throws Exception {
        String eventType ="1";
        log.info("头条收到了夸克回调信息请求流水号{},回调类型为", requestId);
        if (StringUtils.isBlank(requestId)) {
            log.error("头条收到了夸克回调信息请求流水号空");
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(eventType);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,eventType);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);

        //回传的功能控制
        ResponseEntity<Result> ok =dynamicRequestLimiter.getResultResponseEntity(jsonObject, reportDTO);
        if (ok != null) return ok;


        //2.从缓存加载配置
        String url = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        String resultUrl = url + "&event_type=active";
        log.info("账户:{},请求id:{}夸克-头条，请求完整的url为{}", reportDTO.getDspId(), requestId, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账户:{},请求id:{}夸克-头条，响应结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }




}
